package com.winai.launcher.viewModel;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.clj.fastble.BleManager;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.R;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.override.BluetoothCountTimerObserver;
import com.winai.launcher.view.set.SetBluetoothNewActivity;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

/**
 * @author kangshao
 * @date 4/22/21
 * @desc 蓝牙设置——viewModel
 * 　　　　　　　　┏┓　　　┏┓
 * 　　　　　　　┏┛┻━━━┛┻┓
 * 　　　　　　　┃　　　　　　  ┃
 * 　　　　　　　┃　　　━ 　　　┃
 * 　　　　　　　┃　＞　　　＜　┃
 * 　　　　　　　┃　　　　　　　┃
 * 　　　　　　　┃ ...　⌒　... ┃
 * 　　　　　　　┃　　　　　　　┃
 * 　　　　　　　 ┗━┓　　　 ┏━┛
 * 　　　　　　　　　┃　　　┃　Code is far away from bug with the animal protecting
 * 　　　　　　　　　┃　　　┃   神兽保佑,代码无bug
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┗━━━┓
 * 　　　　　　　　　┃　　　　　　　┣┓
 * 　　　　　　　　　┃　　　　　　　┏┛
 * 　　　　　　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　　　　　　┃┫┫　┃┫┫
 * 　　　　　　　　　　┗┻┛　┗┻┛
 */
public class SetBluetoothNewViewModel implements Observer {
    private final MyBluetoothReceiver myBluetoothReceiver;
    private SetBluetoothNewActivity activity;
    public int countdown;//倒计时
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice bluetoothDevice;

    public void setBluetoothDevice(BluetoothDevice bluetoothDevice) {
        this.bluetoothDevice = bluetoothDevice;
    }

    public final ObservableField<String> deviceName = new ObservableField<>();//设备名称
    public final ObservableField<String> linkedDevice = new ObservableField<>();//连接的手机名称
    public final ObservableField<String> buttonText = new ObservableField<>();//按钮文字
    public final ObservableField<String> linkText = new ObservableField<>();//连接状态：未连接，已连接
    public final ObservableField<Boolean> isGreen = new ObservableField<>();//按钮背景颜色：false:灰色，true:绿色
    public final ObservableField<ButtonStatus> buttonStatus = new ObservableField<>();//按钮状态

    public SetBluetoothNewViewModel(SetBluetoothNewActivity setBluetoothNewActivity) {
        this.activity = setBluetoothNewActivity;
        myBluetoothReceiver = new MyBluetoothReceiver(this);
        myBluetoothReceiver.register(activity);

        init(false);
        //添加蓝牙倒计时观察者
        BluetoothCountTimerObserver.getInstance().addObserver(this);
    }

    private void init(boolean isDisableBluetooth) {
        mBluetoothAdapter = BleManager.getInstance().getBluetoothAdapter();

        String bluetoothName = getBluetoothName();
        if (TextUtils.isEmpty(bluetoothName)) {
            buttonStatus.set(ButtonStatus.UNLINK);
            buttonText.set("开始配对");
            deviceName.set(TextUtils.isEmpty(mBluetoothAdapter.getName()) ? "小艾智能养生管家" : mBluetoothAdapter.getName());
            linkText.set("未连接");
            if (isDisableBluetooth) {
                BleManager.getInstance().disableBluetooth();
            }
        } else {
            buttonStatus.set(ButtonStatus.LINKED);
            buttonText.set("断开连接");
            deviceName.set(TextUtils.isEmpty(mBluetoothAdapter.getName()) ? "小艾智能养生管家" : mBluetoothAdapter.getName());
            linkText.set("已连接");
            linkedDevice.set(bluetoothName);
        }
        isGreen.set(true);
    }

    /**
     * @date 4/25/21
     * @desc 获取已连接的蓝牙设备名称
     */
    private String getBluetoothName() {
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {//得到蓝牙状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(mBluetoothAdapter, (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                LogUtils.e("BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                LogUtils.e("devices:" + devices.size());
                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if (isConnected) {
                        LogUtils.e("connected:" + device.getName());
                        setBluetoothDevice(device);
                        return device.getName();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * @date 5/17/21
     * @desc 观察者方法——蓝牙可被发现120s倒计时
     */
    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof Integer) {
            countdown = (int) arg;
            if (countdown > 0) {
                @SuppressLint("StringFormatMatches")
                String ss = String.format(activity.getResources().getString(R.string.djs), countdown);
                buttonText.set(ss);
                isGreen.set(false);
                buttonStatus.set(ButtonStatus.WAIT);
            } else {
                init(true);
            }
        }
    }

    public enum ButtonStatus {
        UNLINK, LINKED, WAIT
    }

    public void clickButton() {
        if (ButtonStatus.UNLINK == buttonStatus.get()) {
            isGreen.set(false);
            buttonStatus.set(ButtonStatus.WAIT);
            BleManager.getInstance().enableBluetooth();
        } else if (ButtonStatus.WAIT == buttonStatus.get()) {
            //倒计时
        } else if (ButtonStatus.LINKED == buttonStatus.get()) {
            //断开连接
            if (bluetoothDevice != null) {
//                BlueToothUtils.getInstance().removeBond(bluetoothDevice);//与设备解除配对
//                BleManager.getInstance().disconnect(new BleDevice(bluetoothDevice));
//                CbtManager.getInstance().disableCancelService();
                BleManager.getInstance().disableBluetooth();
            }
        }
    }

    public void onPause() {
        if (TextUtils.isEmpty(getBluetoothName())) {
            BleManager.getInstance().disableBluetooth();
        }
        try {
            if (myBluetoothReceiver != null) {
                activity.unregisterReceiver(myBluetoothReceiver);
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    private static class MyBluetoothReceiver extends BroadcastReceiver {
        WeakReference<SetBluetoothNewViewModel> weakReference;

        public MyBluetoothReceiver(SetBluetoothNewViewModel activity) {
            weakReference = new WeakReference<>(activity);
        }

        public void register(Context mContext) {
            /**
             * 异步搜索蓝牙设备——广播接收
             */
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.ACTION_BLUETOOTH_DEVICE_CONNECTED);//设备连接成功
            filter.addAction(Constant.ACTION_BLUETOOTH_DEVICE_DISCONNECTED);//设备断开连接
            filter.addAction(Constant.ACTION_BLUETOOTH_STATE_ON);//蓝牙打开
            filter.addAction(Constant.ACTION_BLUETOOTH_STATE_OFF);//蓝牙关闭
            // 注册广播
            mContext.getApplicationContext().registerReceiver(this, filter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra("device");
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            switch (action) {
                case Constant.ACTION_BLUETOOTH_DEVICE_CONNECTED:
                    if (weakReference.get() != null && device != null) {
                        weakReference.get().setBluetoothDevice(device);
                        weakReference.get().linkedDevice.set(device.getName());
                        weakReference.get().isGreen.set(true);
                        weakReference.get().linkText.set("已连接");
                        weakReference.get().buttonText.set("断开连接");
                        weakReference.get().buttonStatus.set(ButtonStatus.LINKED);
                    }
                    GlobalPublisher.Notify(GlobalPublisher.BOND_BLUETOOTH);
                    break;
                case Constant.ACTION_BLUETOOTH_DEVICE_DISCONNECTED:
                case Constant.ACTION_BLUETOOTH_STATE_OFF:
                    if (weakReference.get() != null) {
                        weakReference.get().linkedDevice.set("");
                        weakReference.get().isGreen.set(true);
                        weakReference.get().linkText.set("未连接");
                        weakReference.get().buttonText.set("开始配对");
                        weakReference.get().buttonStatus.set(ButtonStatus.UNLINK);
                    }
                    GlobalPublisher.Notify(GlobalPublisher.BLUETOOTH_DEVICE_DISCONNECTED);
                    break;
            }
        }
    }

}